"""
五子棋游戏API端点

处理与五子棋游戏相关的API请求，包括创建游戏、加入游戏、落子等。
"""

from typing import List, Dict, Any, Optional

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.modules.auth.deps import get_current_user
from app.db.session import get_db
from app.models.user import User
from app.modules.gomoku.schemas.game import (
    GameCreate, GameOut, GameMoveCreate, GameListItem, GameMove
)
from app.modules.gomoku.services import game_service


# 创建路由器
router = APIRouter()


@router.post("/", response_model=GameOut, status_code=status.HTTP_201_CREATED)
async def create_game(
    game_data: GameCreate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    创建新的五子棋游戏
    
    创建一个新的等待对手加入的游戏。
    """
    game = await game_service.create_game(
        db, player_id=current_user.id, board_size=game_data.board_size
    )
    return await _prepare_game_response(db, game.id)


@router.get("/", response_model=List[GameListItem])
async def list_games(
    skip: int = 0,
    limit: int = 10,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取当前用户的游戏列表
    
    返回当前用户参与的所有游戏。
    """
    games = await game_service.get_user_games(
        db, user_id=current_user.id, skip=skip, limit=limit
    )
    return games


@router.get("/waiting", response_model=List[GameListItem])
async def list_waiting_games(
    skip: int = 0,
    limit: int = 10,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取等待加入的游戏列表
    
    返回所有等待对手加入的游戏。
    """
    games = await game_service.get_waiting_games(db, skip=skip, limit=limit)
    return games


@router.get("/{game_id}", response_model=GameOut)
async def get_game(
    game_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取游戏详情
    
    返回指定ID的游戏详细信息。
    """
    return await _prepare_game_response(db, game_id)


@router.post("/{game_id}/join", response_model=GameOut)
async def join_game(
    game_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    加入游戏
    
    加入指定ID的游戏。
    """
    game = await game_service.join_game(db, game_id=game_id, player_id=current_user.id)
    if not game:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="无法加入游戏，可能游戏已开始或不存在"
        )
    return await _prepare_game_response(db, game_id)


@router.post("/{game_id}/move", response_model=GameOut)
async def make_move(
    game_id: int,
    move_data: GameMoveCreate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    执行落子
    
    在指定游戏中落子。
    """
    game, game_move, is_win = await game_service.make_move(
        db, game_id=game_id, user_id=current_user.id, move=move_data
    )
    if not game or not game_move:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="无效的落子"
        )
    
    response = await _prepare_game_response(db, game_id)
    return response


@router.post("/{game_id}/resign", response_model=GameOut)
async def resign_game(
    game_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    认输
    
    在指定游戏中认输。
    """
    game = await game_service.resign_game(db, game_id=game_id, user_id=current_user.id)
    if not game:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="无法认输，可能游戏已结束或不存在"
        )
    return await _prepare_game_response(db, game_id)


# 辅助函数
async def _prepare_game_response(db: AsyncSession, game_id: int) -> Dict[str, Any]:
    """准备游戏响应数据"""
    game = await game_service.get_game(db, game_id=game_id)
    if not game:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="游戏不存在"
        )
    
    # 解析棋盘状态
    from app.modules.gomoku.services.game_logic import gomoku_logic
    board_state = gomoku_logic.parse_board_state(game.board_state)
    
    # 构建响应
    response = {
        "id": game.id,
        "status": game.status.value,
        "board_size": game.board_size,
        "board": board_state["board"],
        "last_move": board_state.get("last_move"),
        "current_turn": game.current_turn.value if game.current_turn else None,
        "player1": {
            "id": game.player1.id,
            "username": game.player1.username,
            "color": game.player1_color.value if game.player1_color else None,
        },
        "moves": [
            {
                "id": move.id,
                "game_id": move.game_id,
                "user_id": move.user_id,
                "x": move.x,
                "y": move.y,
                "color": move.color.value,
                "move_number": move.move_number,
                "created_at": move.created_at
            }
            for move in sorted(game.moves, key=lambda m: m.move_number)
        ],
        "started_at": game.started_at,
        "created_at": game.created_at,
    }
    
    # 添加player2信息（如果存在）
    if game.player2:
        response["player2"] = {
            "id": game.player2.id,
            "username": game.player2.username,
            "color": game.player2_color.value if game.player2_color else None,
        }
    else:
        response["player2"] = None
    
    # 添加获胜者信息（如果存在）
    winner = None
    if game.winner_id:
        if game.player1_id == game.winner_id:
            winner = {
                "id": game.player1.id,
                "username": game.player1.username,
            }
        elif game.player2 and game.player2_id == game.winner_id:
            winner = {
                "id": game.player2.id,
                "username": game.player2.username,
            }
    response["winner"] = winner
    
    return response 